<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>游戏</title>
        <style>
            *{
                box-sizing: border-box;
            }
            html,body,#game{
                width: 100%;
                height: 100%;
            }
            body{
                overflow: hidden;
                margin: 0;
                background-image: url(img/personage/宝贝6.jpg);
                background-size: 100% 100%;
            }
            #game{
                position: relative;
            }
            .rect{
                height: 50px;
                position: absolute;
            }
            .key{
                height: 50px;
                position: absolute;
                border: 1px solid black;
                text-align: center;
                line-height: 50px;
                font-size: 50px;
            }
            
            #score{
                position: absolute;
                top: 10px;
                right: 10px;
                color: gold;
                font-size: 50px;
                z-index: 10;
            }
        </style>
    </head>
    <body>
        <!-- 背景音乐 -->
        <audio id="bg"></audio>
        <!-- 得分 -->
        <audio src=".//节奏大师/音效/得分.mp3" id="get"></audio>
        <!-- 丢失 -->
        <audio src=".//节奏大师/音效/丢失.mp3" id="lose"></audio>
        <!-- 游戏失败 -->
        <audio src=".//节奏大师/音效/失败.mp3" id="fail"></audio>
        <!-- 分数 -->
        <div id="score">0</div>
        <div id="game">
            <!-- 下落的方块 -->
            <div id="rect-box">
                
            </div>
            <!-- 按键 -->
            <div id="key-box">

            </div>
        </div>
		
    </body>
    <script src="detect-collisions.js"></script>
    <script>
        // 分数
        var score = 0;
        // 丢失
        var lose = 0;
        // 歌曲
        var music = localStorage.getItem("music");
        // 难以程度
        var diffi = localStorage.getItem("diffi");
        // 速率
        var speed = localStorage.getItem("speed");
       
        // 放歌
        var bg = document.getElementById("bg");
        bg.src ="./musics" + musics + ".mp3";
        bg.play();
        bg.loop = true;

        // 封装方法：返回#A85CC3的随机数
        function gr(){
            var info = "0123456789ABCDEF"
            var str = "#";
            for(var i = 0; i < 6; i++){
                var random = Math.floor(Math.random()*16);
                str += info[random];
            }
            return str;
        }

        // 布局下落先算好(列)
        // for(var i = 0; i < diffi; i++){
        //     var rect = document.createElement("div");
        //     rect.classList.add("rect");
        //     rect.style.width = (100/diffi) + "%";
        //     rect.style.backgroundColor = gr();
        //     rect.style.top = 0;
        //     rect.style.left = (100 / diffi)*i + "%";
        //     document.getElementById("rect-box").appendChild(rect);
        // }


        // 一开始就先生成30个rect
        var rects = [];
        for(var i = 0; i < 30; i++){
            var rect = document.createElement("div");
            rect.classList.add("rect");
            rect.style.width = (100 - (diffi * 1 + 1) * 3) / diffi * 1 + "%";
            rect.style.backgroundColor = gr();
            rect.style.top = -50 + "px";
            rect.style.left = 0;
            // 自定义属性（表示没有被使用）
            rect.isUsed = false;
            document.getElementById("rect-box").appendChild(rect);
            rects.push(rect);
        }


        // rect下落（随机列）
        setInterval(function(){
            var rect = rects.find(function(ele){
                return !ele.isUsed;
            });
            if (!rect) return;
            rect.isUsed = true;
            // 找到一个没有被使用的，先布局好top和left
            rect.style.top = -50 + "px";
            rect.style.left = 3 + ((100 - (diffi * 1 + 1) * 3) / diffi * 1 + 3) * (Math.floor(Math.random() * diffi)) + "%";
            // 开始下落
            var timer = setInterval(function () {
                // rect身上有个自定义属性，保存的是控制自己移动的定时器
                rect.timer = timer;
                rect.style.top = parseInt(rect.style.top) + 10 + "px";
                if (parseInt(rect.style.top) > document.body.clientHeight) {
                    // 丢失了
                    if (rect.isUsed) {
                        lose++;
                        if (lose >= 10) {
                            var get = document.getElementById("fail");
                            get.load();
                            get.play();
                            var com = confirm("游戏结束");
                            location.href = "游戏结束.html";
                            // 获取系统时间
                            var time = getTime();
                            var username = localStorage.getItem("username");
                            var record = {
                            	username:username,
                            	time:time,
                            	score:score
                            }
                            var records = JSON.parse(localStorage.getItem("records"));
                            if (!records) {
                            	records = [];
                            }
                            records.push(record);
                            localStorage.setItem("records",JSON.stringify(records));
                            
                        }
                        var get = document.getElementById("lose");
                        get.load();
                        get.play();
                    }
                    rect.isUsed = false;
                    clearInterval(timer);
                }
            }, speed);
        // speed 越大时间越短，diffi 越大时间越短 
        },1000/(Math.pow(1.1,diffi)) - (50 - speed)*20);

        
        // 布局下面的按键
        var keysStr = ["Q", "W", "E", "R", "T", "Y", "U", "I"];
        var keys = [];
        for(var i = 0; i < diffi; i++){
            var key = document.createElement("div");
            key.classList.add("key");
            key.style.width = (100-(diffi*1+1)*3) / diffi*1 + "%";
            key.style.backgroundColor = "white";
            key.style.bottom = 0;
            key.style.left = 3 + ((100 - (diffi * 1 + 1) * 3) / diffi * 1 + 3)*i + "%";
            key.textContent = keysStr[i];
            // 给key自定义属性 kc，保存对应内容的ASCII码值
            key.kc = keysStr[i].charCodeAt(0);
            document.getElementById("key-box").appendChild(key);
            keys.push(key);
        }

        document.onkeydown = function(e){
            var key = keys.find(function(ele){
                return ele.kc == e.keyCode;
            });
            if (key) {
                key.style.backgroundColor = "red";
                // 检测碰撞
                for(var i = 0; i < rects.length; i++){
                    if (rects[i].isUsed && collision(key, rects[i])) {
                        // console.log("碰撞了");
                        // 把isUsed置为false，方便下次重用
                        rects[i].isUsed = false;
                        // 清除移动自己的定时器
                        clearInterval(rects[i].timer);
                        // 移到屏幕的下方
                        rects[i].style.top = document.body.clientHeight + "px";

                        score ++;
                        document.getElementById("score").textContent = "分数：" + score;
                        // 播放音效
                        var get = document.getElementById("get");
                        get.load();
                        get.play();
                    }
                }
            }
        }
        document.onkeyup = function(e){
            var key = keys.find(function (ele) {
                return ele.kc == e.keyCode;
            });
            if (key) {
                key.style.backgroundColor = "green";
            }
        }
    </script>
</html>